﻿using System;
using System.Buffers;
using System.Threading;

namespace Ndns.Packet.Parser.Helpers
{
    struct ArrayPoolLease<T> : IDisposable
    {
        private ArrayPool<T> _pool;
        private T[] _array;
        private bool _clearArrayOnReturn;

        public T[] Array => _array;

        public ArrayPoolLease(T[] array)
        {
            _pool = null;
            _clearArrayOnReturn = false;
            _array = array;
        }
        public ArrayPoolLease(ArrayPool<T> pool, T[] array, bool clearArrayOnReturn)
        {
            _pool = pool;
            _clearArrayOnReturn = clearArrayOnReturn;
            _array = array;
        }

        void IDisposable.Dispose()
        {
            var pool = Interlocked.Exchange(ref _pool, null);
            if (pool != null && _array != null)
            {
                pool.Return(_array, _clearArrayOnReturn);
            }
        }
    }

}
